package com.itheima.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.pojo.Result;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class BaseController {

    public static <T> T jsonStrToJavaObject(HttpServletRequest request,Class<T> clazz)  {
        try {
            ObjectMapper om = new ObjectMapper();
            // 将json字符串转成java对象
            T obj = om.readValue(request.getInputStream(), clazz);
            return obj;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void responseJson(HttpServletResponse response, Result result)  {
        response.setContentType("application/json;charset=utf-8");
        try {
            ObjectMapper om = new ObjectMapper();
            String jsonResult = om.writeValueAsString(result);
            System.out.println(jsonResult);
            response.getWriter().print(jsonResult);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
